package com.demo.core;

import java.net.InetSocketAddress;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ElasticSearchTransportClient {

	private static TransportClient transportClient;

	@Autowired
	ElasticSearchConfig elasticSearchConfig;
	
	private void initElasticSearchTransportClient(ElasticSearchConfig config) {
		Settings settings = Settings.settingsBuilder()
				.put("cluster.name", config.getClusterName())
				.put("client.transport.ignore_cluster_name", true)
				.build();
		transportClient = TransportClient.builder().settings(settings).build();

		for (com.demo.core.ElasticSearchConfig.Client c : config
				.getAllClients()) {
			transportClient.addTransportAddress(new InetSocketTransportAddress(
					new InetSocketAddress(c.getHost(), c.getPort())));
		}
	}

	public TransportClient getInstance() {
		if(transportClient==null){
			initElasticSearchTransportClient(elasticSearchConfig);
		}
		return transportClient;
	}

}
